<template>
  <div style="margin: 0 20px;">
    <el-table :data="tableData" stripe style="width: 100%">
      <el-table-column prop="id" label="ID" width="60"/>
      <el-table-column prop="title" label="标题" :show-overflow-tooltip="true"/>
      <el-table-column prop="brief" label="简介" width="300" :show-overflow-tooltip="true"/>
      <el-table-column prop="salePrice" label="价格" width="100"/>
      <el-table-column label="操作" width="100" align="center" v-if="loginInfo.token">
        <template slot-scope="scope">
          <el-button type="primary" size="mini"
                     @click="addToCart(scope.row)">添加购物车
          </el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
export default {
  data() {
    return {
      loginInfo: {
        token: ''
      },
      goodsListUrl: 'http://localhost:19282/goods/list-by-recommend',
      addToCartUrl: 'http://localhost:19282/carts/add',
      tableData: []
    }
  },
  methods: {
    loadLoginInfo() {
      let loginInfoString = localStorage.getItem('alipay_loginInfo');
      if (loginInfoString) {
        this.loginInfo = JSON.parse(loginInfoString);
      }
    },
    addToCart(goods) {
      if (this.loginInfo.token) {
        let params = 'goodsNum=1&goodsId=' + goods.id;
        this.axios
            .create({'headers': {'Authorization': this.loginInfo.token}})
            .post(this.addToCartUrl, params).then((response) => {
          let jsonResult = response.data;
          if (jsonResult.state == 20000) {
            this.$message({
              message: '添加成功！',
              type: 'success'
            });
          } else {
            this.$message.error(jsonResult.message);
          }
        });
      }
    },
    loadGoodsList() {
      this.axios.get(this.goodsListUrl).then((response) => {
        this.tableData = response.data.data.list;
      });
    }
  },
  created() {
    this.loadLoginInfo();
  },
  mounted() {
    this.loadGoodsList();
  }
}
</script>